const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database({
  env: 'test-767203960-6g9qt175a903732b'
}) //对云数据库初始化
/* const rp = require('request-promise'); */
const axios = require('axios')
const URL = 'https://apis.imooc.com/personalized?icode=806BEDDEE4FEFB60'
const playlistCollection = db.collection('playlist')
const MAX_LIMIT = 100
// 云函数入口函数                               
exports.main = async (event, context) => {
  const countResult = await playlistCollection.count()
  const total = countResult.total
  const bathTimes = Math.ceil(total / MAX_LIMIT)
  const tasks = []
  for (let i = 0; i < bathTimes; i++) {
    let promise = playlistCollection.skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    tasks.push(promise)
  }
  let list = {
    data: []
  }
  if (tasks.length > 0) {
    list = (await Promise.all(tasks)).reduce((acc, cur) => {
      return {
        data: acc.data.concat(cur.data)
      }
    })

  }


  const {
    data
  } = await axios.get(URL)
  if (data.code >= 1000) {
    console.log(data.msg)
    return 0
  }
  const playlist = data.result

  //去重
  const newData = []
  for (let i = 0, len1 = playlist.length; i < len1; i++) {
    let flag = true //true  表示不重复
    for (let j = 0, len2 = list.data.length; j < len2; j++) {
      if (playlist[i].id === list.data[j].id) {
        flag = false
        break
      }
    }
    if (flag) {
     playlist[i].createTime = db.serverDate()
      newData.push(playlist[i])
    }
  }
  //db.collecticon（集合名）取到数据库里面的集合。再通过add方法
  if (newData.length > 0) {
    //playlistCollection从服务器段获取的数据
    await playlistCollection.add({
      //扩展运算符  ...playlist   意思是playlist里面所有信息
      data: [...newData]
    }).then((res) => {
      console.log('插入成功')
    }).catch((err) => {
      console.log('插入失败')
    })
  
  }

  return newData.length


}